import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<String> names = ["a", "b", "c", "d", "e", "f"];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'widget key 测试',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: ListView(
          children: names
              .map((e) => StatefulItem(
                    e,
                    // 传入key参数后，就是预期结果
                    key: Key(e),
                  ))
              .toList(),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.delete),
          onPressed: () {
            // 重新构建调用widget build方法，由于产生随机颜色在build中，所以每次点击删除都会改变item颜色
            setState(() {
              names.removeAt(0);
            });
          },
        ),
      ),
    );
  }
}

class StatelessItem extends StatelessWidget {
  final String name;

  StatelessItem(this.name, {Key key}) : super(key: key);

  Color randomColor = Color.fromARGB(
      255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      color: randomColor,
      child: Text(
        name,
        style: TextStyle(fontSize: 50, color: Colors.white),
      ),
    );
  }
}

class StatefulItem extends StatefulWidget {
  final String name;

  StatefulItem(this.name, {Key key}) : super(key: key);

  @override
  _StatefulItemState createState() => _StatefulItemState();
}

// 颜色在state中生产，就不会重新产生新颜色，但是效果是数字从顶部删除，颜色从尾部删除
// 原因：重新构建时会判断是否需要重新绘制widget canUpdate->由于没有设置key，runtimeType相同，返回false，所以会复用
// item remove后，后面的item会复用前面的state，而最后一个item没有引用了就被系统回收 unmount
class _StatefulItemState extends State<StatefulItem> {
  Color randomColor = Color.fromARGB(
      255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 80,
      color: randomColor,
      child: Text(
        widget.name,
        style: TextStyle(fontSize: 50, color: Colors.white),
      ),
    );
  }
}


